package com.k2.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.k2.common.utils.HttpUtils;
import com.k2.common.utils.R;
import com.k2.common.vo.MemberVo;
import com.k2.common.vo.UserRegisterVo;
import com.k2.gulimall.auth.service.MemberService;
import com.k2.gulimall.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

import static com.k2.common.constant.AuthServerConstant.LOGIN_USER;


@Slf4j
@Controller
public class OAuth2Controller {

    @Autowired
    private MemberService memberService;


    @GetMapping(value = "/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {

        Map<String, String> map = new HashMap<>();
        map.put("client_id","296388511");
        map.put("client_secret","fd79a58b529631ed909f0efe15e3b9f4");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://localhost:20000/oauth2.0/weibo/success");
        map.put("code",code);

        //1、根据用户授权返回的code换取access_token
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<>(), map, new HashMap<>());

        //2、处理
        if (response.getStatusLine().getStatusCode() == 200) {
            //获取到了access_token,转为通用社交登录对象
            String json = EntityUtils.toString(response.getEntity());
            //String json = JSON.toJSONString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);

            //知道了哪个社交用户
            //1）、当前用户如果是第一次进网站，自动注册进来（为当前社交用户生成一个会员信息，以后这个社交账号就对应指定的会员）
            //登录或者注册这个社交用户
            //调用远程服务
            Object userRegisterVo = session.getAttribute("userIp");
            Map<String,String> jsonMap = new HashMap<>();
            jsonMap.put("socialUser",json);
            jsonMap.put("userRegisterVo",JSON.toJSONString(userRegisterVo));
            R oauthLogin = memberService.oauthLogin(jsonMap);
            if (oauthLogin.getCode() == 0) {
                MemberVo data = oauthLogin.getData(new TypeReference<MemberVo>() {});
                log.info("登录成功：用户信息：{}",data.toString());
                session.setAttribute(LOGIN_USER,data);
                
                //2、登录成功跳回首页
                return "redirect:http://localhost:10000/index.html";
            } else {

                return "redirect:http://localhost:20000/login.html";
            }

        } else {
            return "redirect:http://localhost:20000/login.html";
        }

    }

}
